import router, { asyncRouters } from './router'
import store from './store'

// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token
  NProgress.start()
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      // vuex异步请求调用

      if (!store.getters.userId) {
        const menus = await store.dispatch('user/userinof')

        const Mymenus = asyncRouters.filter(routers => {
          return menus.menus.includes(routers.children[0].name)
        })
        Mymenus.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(Mymenus)
        store.commit('permission/setRouters', Mymenus)
        console.log(to.path, 'path', menus)
        const Mymenus1 = []
        menus.menus.forEach(itme => {
          Mymenus1.push('/' + itme)
        })
        console.log(to, '我是to')
        if (to.path === '/employees/detail') next({ path: to.fullPath })
        else Mymenus1.includes(to.path) ? next({ path: to.path, replace: true }) : next({ path: '/', replace: true })
      }

      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
  NProgress.done()
})
router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})
router.afterEach((to, from) => {
  NProgress.done()
})
